package com.atguigu.study.base;


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Ticket //资源类，面向对象编程 ，对象 = Field + Method
{
    private int number = 50;

    /*public synchronized void sale()
    {
        if(number > 0)
        {
            System.out.println(Thread.currentThread().getName()+"\t"+"卖出第："+(number--)+"\t 还剩下："+number);
        }
    }*/

    private final Lock lock = new ReentrantLock(); // ReentrantLock 叫可重入锁+默认悲观锁+默认非公平锁

    public void sale()
    {
        lock.lock();
        try
        {
            if(number > 0)
            {
                System.out.println(Thread.currentThread().getName()+"\t"+"卖出第："+(number--)+"\t 还剩下："+number);
            }
        }finally {
            lock.unlock();
        }
    }


}


/**
 * @auther zzyybs@126.com
 * @Date 2025-04-21 22:00
 * @Description: 三个售票员  卖出 50张 票
 *
 * juc小口诀第一式
 *
 * 1 在高内聚低耦合前提下，    线程      操作      资源类
 */
public class SaleTicketDemo
{
    public static void main(String[] args) //只是程序的入口
    {
        //Thread(Runnable target, String name) Allocates a new Thread object.

        Ticket ticket = new Ticket();

        /* V1
        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                for (int i = 1; i <= 50; i++) {
                    ticket.sale();
                }
            }
        }, "A").start();

        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                for (int i = 1; i <= 50; i++) {
                    ticket.sale();
                }
            }
        }, "B").start();

        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                for (int i = 1; i <= 50; i++) {
                    ticket.sale();
                }
            }
        }, "C").start();*/

        // V2
/*        new Thread(() -> { for (int i = 1; i <= 50; i++)  ticket.sale();}, "A").start();
        new Thread(() -> { for (int i = 1; i <= 50; i++)  ticket.sale();}, "B").start();
        new Thread(() -> { for (int i = 1; i <= 50; i++)  ticket.sale();}, "C").start();*/

        //V3 线程池版本

        ExecutorService threadPool = Executors.newFixedThreadPool(3);

        try
        {
            for (int i = 0; i < 50; i++) {
                threadPool.execute(() -> {
                    ticket.sale();
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPool.shutdown();
        }

    }
}


